<template>
  <el-container>
    <el-header style="background-color: rgb(38,47,62);color: aliceblue">
      <strong style="float: left;size: 1000px;font-size: 25px"><i class="el-icon-school"></i> 美奥口腔后台管理系统</strong>

      <div class="header-avatar">
        <!--<el-avatar :src="avatarUrl" shape="circle" size="small"></el-avatar>-->
        <el-avatar size="medium" :src="avatarUrl"></el-avatar>
        <el-dropdown style="color: aliceblue">
						<span class="el-dropdown-link"><span style="color: #10e0d9">欢迎您:</span>
						{{ user.username }}<i class="el-icon-arrow-down el-icon--right"></i>
						</span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="retireInfo">个人中心</el-dropdown-item>
            <el-dropdown-item @click.native="Toreset">修改密码</el-dropdown-item>
            <el-dropdown-item @click.native="drawer = true">修改头像</el-dropdown-item>
            <el-dropdown-item @click.native="ToHospital">查看医院信息</el-dropdown-item>
            <el-dropdown-item @click.native="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>

        <span @click="ToChat">聊天室</span>
      </div>

    </el-header>
    <el-container>
      <el-aside width="200px">
        <Sidebar></Sidebar>
      </el-aside>
      <el-main>
        <el-tabs
            v-model="activeTab"
            type="card"
            closable
            @tab-remove="removeTab"
            @tab-click="clickBtn"
        >
          <el-tab-pane
              :key="index"
              v-for="(item, index) in tabList"
              :label="item.title"
              :name="item.path"
          >
          </el-tab-pane>
        </el-tabs>
        <router-view></router-view>
      </el-main>

      <!--      上传头像-->
      <el-drawer title="上传头像" :visible.sync="drawer" :with-header="false">
        <h1 style="font-size: 30px; margin-top: 20px; margin-left: 200px">
          修改头像
        </h1>
        <!--      <el-upload-->
        <!--          class="avatar-uploader"-->
        <!--          action=""-->
        <!--          :http-request="uploadFun"-->
        <!--          :show-file-list="true"-->
        <!--          :on-success="handleAvatarSuccess"-->
        <!--          :before-upload="beforeAvatarUpload"-->
        <!--      >-->
        <!--        <img v-if="imageUrl" :src="imageUrl" class="avatarUpdate"/>-->
        <!--        <i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
        <!--      </el-upload>-->
        <el-upload
            class="upload-demo"
            action="https://jsonplaceholder.typicode.com/posts/"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :http-request="uploadFun"
            :show-file-list="true"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :file-list="fileList"
            list-type="picture">
          <el-button size="small" type="success">修改头像</el-button>

          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
        <el-button size="small" type="success" @click="Out">返回首页</el-button>
      </el-drawer>
    </el-container>
    <!--    <el-footer style="flex: 0 0 60px; color: #333"-->
    <!--    >&copy; 版权所有 智心医疗-->
    <!--    </el-footer-->
    <!--    >-->

  </el-container>
</template>

<script>

import Sidebar from "../components/Sidebar";

import Tabs from "@/components/Tabs";


import store from "@/store";

import Hello from "@/components/Hello.vue";


export default {
  name: "IndexView",
  components: {

    Sidebar, Tabs

  },
  data() {
    return {
      // 文件上传
      fileList: [{name: '可可爱爱李知恩', url: 'https://img1.baidu.com/it/u=145565177,2077873995&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=889'},
        {name: 'IU！！！', url: 'https://img0.baidu.com/it/u=3254722408,1664873130&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500'}],
      avatarUrl: '', // 初始化avatarUrl为空
      user: '',   // 姓名
      drawer: false,   // 控制修改头像的组件
      // 当前活跃的tabs
      activeTab: '',
      id: "",
      dialogFormVisible: false,
      form: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      formLabelWidth: '120px',

    }
  },
  computed: {
    tabList() {
      return store.getters['getTabs']
    },
  },
  watch: {
    $route: function () {
      this.setActiveTab()
      this.addTab()
    },
  },
  created() {
    // 在组件创建时从sessionStorage中获取头像链接
    this.avatarUrl = sessionStorage.getItem('icon');
    this.avatarUrl = JSON.parse(this.avatarUrl);
    this.user = sessionStorage.getItem('user');
    console.log('link>>>>>>>>>>', this.avatarUrl)
    this.user = JSON.parse(this.user);
    console.log('link>>>>>>>>>>', typeof user)
  },
  mounted() {
    this.beforeRefresh()
    this.setActiveTab()
    this.addTab()
  },
  methods: {
    ToHospital(){
      this.$router.push({
              path: "/hospitalinfo",
            });
    },
    ToChat(){
      this.$router.push({
              path: "/chat",
            });
    },
    Toreset(){
     this.$router.push({
                path: "/modifypwd",})
    },
    Out(){
      this.$router.push({ name: 'index' })
      // this.$router.push({path: index})
      location.reload()
    },
    handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
    // 头像上传方法
    uploadFun(param) {
      console.log(param)
      var data = new FormData(); //创建form对象
      let user = this.$getSessionStorage('user')
      let username = user.username
      data.append('file', param.file);
      data.append('user', username);
      var config = {
        headers: {'Content-Type': 'multipart/form-data'}
      };  //添加请求头
      this.$axios.post(this.$settings.BASE_URL + 'user/head/upload_head/', data, config)//
          .then(response => {
            console.log(response)
            if (response.data.code === 100) {
              this.$setSessionStorage('icon', response.data.icon)
              this.squareUrl = response.data.icon
              this.$message({
                message: response.data.msg,
                type: 'success',
                duration: 1000
              });
            }
          })
          .catch(({err}) => {

          })
    },
    handleAvatarSuccess(res, file) {
      console.log(res)
      console.log(file)
      this.imageUrl = URL.createObjectURL(file.raw);
      console.log(this.imageUrl)
    },
    // 头像上传校验
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2;
      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!')
      // }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
      // isJPG &&
    },
    //修改个人信息
    retireInfo(){
      this.$router.push({
              path: "/info",
            });
    },
    //退出登录
    logout() {
      this.$confirm("确认退出登录？")
          .then((_) => {
            sessionStorage.clear()
            console.log("已清空session，正在跳转到登录页面");
            console.log(this.$setSessionStorage('user'));
            this.$router.push({
              path: "/",
            });
          })
          .catch((_) => {
          });
    },
    // 设置活跃的tab
    setActiveTab() {
      this.activeTab = this.$route.path
    },
    // 添加tab
    addTab() {
      const {path, meta} = this.$route
      const tab = {
        path,
        title: meta.title,
      }
      store.commit('addTab', tab)
    },
    // 点击tab
    clickBtn(tab) {
      const {name} = tab
      this.$router.push({path: name})
      location.reload()
    },

    // 删除tab

    removeTab(target) {
      let active = this.activeTab
      const tabs = this.tabList

      if (tabs.length === 1) return // 只有一个标签页时不允许删除

      if (active === target) {
        const index = tabs.findIndex(tab => tab.path === target)
        if (index !== -1) {
          // 如果删除的是当前活跃的标签，将活跃标签设置为上一个或下一个
          const nextTab = tabs[index + 1] || tabs[index - 1]
          if (nextTab) {
            this.activeTab = nextTab.path
            // 在删除标签页后，更新URL
            window.history.pushState(null, '', nextTab.path);
          }
        }
      }

      // 更新当前激活的标签和标签列表
      store.state.tabList = tabs.filter(tab => tab.path !== target)
      location.reload();
    },

    // 解决刷新数据丢失问题
    beforeRefresh() {
      window.addEventListener('beforeunload', () => {
        sessionStorage.setItem('tabsView', JSON.stringify(this.tabList))
      })
      let tabSession = sessionStorage.getItem('tabsView')
      if (tabSession) {
        let oldTabs = JSON.parse(tabSession)
        if (oldTabs.length > 0) {
          store.state.tabList = oldTabs
        }
      }
    },
  },
}
</script>

<style scoped>


.el-container {
  padding: 0;
  margin: 0;
  height: 100%;
}

.header-avatar {
  float: right;
  width: 210px;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.el-dropdown-link {
  cursor: pointer;
}

.el-header {
  background-color: #17B3A3;
  color: #333;
  text-align: center;
  line-height: 60px;
}

.el-aside {
  background-color: #D3DCE6;
  color: #333;
  line-height: 200px;
}

.el-main {
  color: #333;
  padding: 0;
}

a {
  text-decoration: none;
}
</style>